package com.sc.nft.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import com.sc.nft.dao.PrivilegeDao;
import com.sc.nft.dao.PrivilegeUseLogDao;
import com.sc.nft.dao.UserCollectionDao;
import com.sc.nft.entity.Privilege;
import com.sc.nft.entity.UserCollection;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.sc.nft.service.PrivilegeUseLogService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 优先购使用情况表服务接口实现
 *
 * @author kancy
 * @since 2022-07-03 15:04:39
 * @description 由 Mybatisplus Code Generator 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PrivilegeUseLogServiceImpl implements PrivilegeUseLogService {
    private final PrivilegeUseLogDao privilegeUseLogDao;
    private final PrivilegeDao privilegeDao;
    private final UserCollectionDao userCollectionDao;

    @Override
    public int getLastFirstPayTime(Long userId) {

        List<UserCollection> userCollections =  userCollectionDao.getAllPrivilegeByUserId(userId);
        if(CollUtil.isEmpty(userCollections)){
            return 0;
        }
        List<Privilege> privilegeList = privilegeDao.list();
        if(CollUtil.isEmpty(privilegeList)){
            return 0;
        }
        Map<Long,Privilege> privilegeMap = privilegeList.stream().collect( Collectors.toMap(Privilege::getCollectionId,d->d));
        int sum=0;
        for (UserCollection userCollection : userCollections) {
            sum+=privilegeMap.get(userCollection.getCollectionId()).getFirstPayTime();
        }
        if(sum<1) {
            return 0;
        }
        String yearMonth = DateTime.now().toString("yyyyMM");
        List<String> uuids = userCollections.stream().map(UserCollection::getCollectionUuid).collect(Collectors.toList());
        int payTime=0;
        for (String uuid : uuids) {
            payTime+= privilegeUseLogDao.getFirstCountByRecordMonth(yearMonth,uuid);
        }
        return sum>payTime?sum-payTime:0;
    }

    @Override
    public String getCurrentUUid(DateTime dateTime, Long userId) {
        List<UserCollection> userCollections =  userCollectionDao.getAllPrivilegeByUserId(userId);
        for (UserCollection userCollection : userCollections) {
            Privilege privilege = privilegeDao.getByCollectionId(userCollection.getCollectionId());
            int count = privilegeUseLogDao.getFirstCount(dateTime.toString("yyyyMM"),userCollection.getCollectionUuid());
            if(privilege.getFirstPayTime()>count){
                return userCollection.getCollectionUuid();
            }
        }
        return null;
    }
}